package framework.util.shiro;

import framework.bo.SysUser;
import framework.service.SysUserService;
import framework.util.layui._LayuiUtil;
import framework.util.queryFilter.service.impl.QueryFilter;
import framework.util.queryFilter.vo.Where;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.pam.UnsupportedTokenException;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 吴宇亮 on 2019/7/5 23:02
 */
public class MysqlRealm extends AuthenticatingRealm {

    @Resource
    private SysUserService sysUserService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //把AuthenticationToken 转换成 UsernamePasswordToken
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)token;

        //获取用户的账号名
        String username = usernamePasswordToken.getUsername();

        //查询数据库，该账号对应的用户记录
        QueryFilter filter = new QueryFilter(_LayuiUtil.FIRST_PAGE, Integer.MAX_VALUE);
        filter.where(SysUser.ACCOUNT, Where.eq, username);
        SysUser sysUser = sysUserService.get(filter);

        //若用户不存在，则抛出异常
        if(null == sysUser){
            throw new UnsupportedTokenException("不存在【" + username + "】的账号");
        }
        SecurityUtils.getSubject().getSession().setAttribute(_ShiroUtil.CURRENT_USER, sysUser);

        //密码认证交给shiro去处理
        //注意这里传入的是数据库的真正的密码，因为shiro已经有前端的密码了，要对比密码是否正确，得给shiro后端的正确的密码，shiro才能对比
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, sysUser.getPassword(), ByteSource.Util.bytes(sysUser.getAccount()), this.getName());
        return info;
    }

}
